class DBManager {
    //数据库管理类的构造函数，包含两个构造参数，数据库名称和数据库版本,数据库版本如果不指定默认为1；
    constructor(DBname, DBversion) {
        this.DBname = DBname;
        this.DBversion = DBversion || 1;
        this.currentDB = null; //当前数据库
    }
    openDB() {
        var request = window.indexedDB.open(this.DBname, this.DBversion);
        //打开数据库失败的回调
        request.onerror = function (e) {
            console.log(e.currentTarget.error.message);
        }.bind(this);
        //打开数据库成功的回调
        request.onsuccess = function (e) {
            this.currentDB = e.target.result;
            console.log(this.currentDB.name + ' database is already opened!');
        }.bind(this);
        //数据库升级的回调
        request.onupgradeneeded = function (e) {
            console.log('database version is already upgrade to ' + this.DBversion);
            this.currentDB = e.target.result;
            if (!this.currentDB.objectStoreNames.contains('students')) {
                //指定一个键为主键
                this.currentDB.createObjectStore('students', { keyPath: "id" });
                //指定为主键自增模式
                //db.createObjectStore('students',{autoIncrement: true});
            }
        }.bind(this);
    }
    //关闭数据库的方法
    closeDB() {
        this.currentDB.close();
        console.log(this.currentDB.name + ' database is already closed!');
    }
    //删除数据库的方法
    deleteDB() {
        window.indexedDB.deleteDatabase(this.DBname);
        console.log(this.DBname + ' database is already deleted!');
    }
    //根据storeName获取对应store的方法
    getStoreByName(storeName) {
        var transaction = this.currentDB.transaction(storeName, 'readwrite');
        return transaction.objectStore(storeName);
    }
}
var db;
window.onload = function () {
    db = new DBManager('testDB', 2);
    db.openDB();
    // setTimeout(function () {
    //     db.closeDB();
    //     db.deleteDB();
    // }, 500);
}
function addData(){
    const datas=[{
        id:11,
        name:"zhangsan",
        age:24
    },{
        id:12,
        name:"lisi",
        age:30
    },{
        id:13,
        name:"wangwu",
        age:26
    },{
        id:14,
        name:"zhaoliu",
        age:26
    }];
    var store=db.getStoreByName('students');
    for(var i = 0; i<datas.length ; i++){
        store.add(datas[i]);
    }
}
function deleteData(){
    var store=db.getStoreByName('students');
    store.delete('wangwu')
}